package com.demo.lifeinfo.common.mine;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.demo.lifeinfo.R;
import com.demo.lifeinfo.adapter.MyNineImageAdapter;
import com.demo.lifeinfo.app.XBaseActivity;
import com.demo.lifeinfo.entity.News;
import com.demo.lifeinfo.entity.Tab;
import com.demo.lifeinfo.entity.User;
import com.demo.lifeinfo.model.GlideApp;
import com.demo.lifeinfo.widget.CustomPopup;
import com.flyco.roundview.RoundTextView;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.UpdateListener;

/**
 * created by Raymond
 * on 2019-05-04
 */
public class MyPublishAc extends XBaseActivity {
    @BindView(R.id.toolbar_back)
    ImageView toolbarBack;
    @BindView(R.id.textView3)
    TextView textView3;
    @BindView(R.id.toolbar_right_btn)
    RoundTextView toolbarRightBtn;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appBarLayout)
    AppBarLayout appBarLayout;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.smartLayout)
    SmartRefreshLayout smartLayout;

    List<Tab> tabs;
    BaseQuickAdapter<News, BaseViewHolder> adapter;

    User user;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mypublish;
    }

    @Override
    protected void initView() {
        toolbarBack.setVisibility(View.GONE);
        user = (User) getIntent().getSerializableExtra("user");
        if (isLogin()) {
            if (user.getObjectId().equals(BmobUser.getCurrentUser(User.class))) {
                textView3.setText("我的发布");
            } else {
                textView3.setText("Ta的发布");
            }
        } else {
            textView3.setText("Ta的发布");
        }


        tabs = new ArrayList<>();

        tabs.add(new Tab("全部"));
        tabs.add(new Tab("问题"));
        tabs.add(new Tab("趣事"));
        tabs.add(new Tab("其他"));

        for (Tab tab : tabs) {
            tablayout.addTab(tablayout.newTab().setText(tab.getTitle()));
        }
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() > 0) {
                    getData(tab.getPosition());
                } else if (tab.getPosition() == 0) {
                    getData(0);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        adapter = new BaseQuickAdapter<News, BaseViewHolder>(R.layout.item_product) {
            @Override
            protected void convert(BaseViewHolder helper, News item) {
                NineGridImageView nineGridImageView = helper.getView(R.id.nindImgView);
                MyNineImageAdapter imageAdapter = new MyNineImageAdapter();
                nineGridImageView.setAdapter(imageAdapter);
                nineGridImageView.setImagesData(item.getImgs());
                GlideApp.with(MyPublishAc.this)
                        .load(item.getAuthor().getAvatar() == null ? R.mipmap.ic_launcher : item.getAuthor().getAvatar().getFileUrl())
                        .centerCrop()
                        .placeholder(R.mipmap.ic_launcher)
                        .error(R.mipmap.ic_launcher)
                        .circleCrop()
                        .into((ImageView) helper.getView(R.id.circleImageView));
                helper.setText(R.id.textView, TextUtils.isEmpty(item.getAuthor().getNickeName()) ? "匿名" : item.getAuthor().getNickeName());
                helper.setText(R.id.expandable_text, item.getContent());
                helper.setVisible(R.id.btn_look, item.getContent().length() > 80 ? true : false);
                if (BmobUser.isLogin()) {
                    if (user.getObjectId().equals(BmobUser.getCurrentUser(User.class).getObjectId())) {
                        helper.setVisible(R.id.btn_delet, true);
                    } else {
                        helper.setVisible(R.id.btn_delet, false);
                    }
                } else {
                    helper.setVisible(R.id.btn_delet, false);
                }

                helper.addOnClickListener(R.id.btn_look, R.id.btn_delet);

            }
        };
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                News news = (News) adapter.getItem(position);
                if (view.getId() == R.id.btn_look) {
                    new XPopup.Builder(MyPublishAc.this)
                            .asCustom(new CustomPopup(MyPublishAc.this, news.getContent()))
                            .show();
                } else if (view.getId() == R.id.btn_delet) {
                    new XPopup.Builder(MyPublishAc.this).asConfirm("删除", "确认删除该发布？", new OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            deletData(news, position);
                        }
                    }).show();
                }
            }
        });


        recyclerView.setLayoutManager(new LinearLayoutManager(MyPublishAc.this));
        recyclerView.setAdapter(adapter);
        smartLayout.setEnableLoadMore(false);
        smartLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getData(0);
            }
        });
    }

    @Override
    protected void initData() {
        smartLayout.autoRefresh();
    }

    private void getData(int type) {

        BmobQuery<News> query = new BmobQuery<>();
        if (type > 0) {
            showProgressDialog();
            query.order("-createdAt").include("author").addWhereEqualTo("author", user).addWhereEqualTo("type", type).findObjects(new FindListener<News>() {
                @Override
                public void done(List<News> list, BmobException e) {
                    dimssProgressDialog();
                    if (e == null) {
                        adapter.setNewData(list);
                    } else {
                        showError(e.getMessage());
                    }
                }
            });
        } else {
            query.order("-createdAt").include("author").addWhereEqualTo("author", user).findObjects(new FindListener<News>() {
                @Override
                public void done(List<News> list, BmobException e) {
                    smartLayout.finishRefresh();
                    if (e == null) {
                        adapter.setNewData(list);
                    } else {
                        showError(e.getMessage());
                    }
                }
            });
        }

    }

    private void deletData(News news, int index) {
        news.delete(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (e == null) {
                    adapter.remove(index);
                } else {
                    showError(e.getMessage());
                }
            }
        });
    }
}
